package com.example.campus.handler;

import com.example.campus.exception.BaseException;
import com.example.campus.result.Result;
import com.example.campus.utils.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获参数异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(IllegalArgumentException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //报错信息：Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理参数检验异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException ex){
        log.error("异常信息：{}", ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("不是一个合法的电子邮件地址")) {
            return Result.error(MessageConstant.ILLEGAL_EMAIL);
        }
        if (message.contains("需要匹配正则表达式\"^\\S{5,16}$\"")) {
            return Result.error(MessageConstant.ILLEGAL_USERNAME_OR_PASSWORD);
        }
        if (message.contains("需要匹配正则表达式\"^1[3-9]\\d{9}$\"")) {
            return Result.error(MessageConstant.ILLEGAL_PHONE);
        }
        if (message.contains("不能为null")) {
            return Result.error(MessageConstant.ILLEGAL_ID);
        }
        if (message.contains("不能为空")) {
            return Result.error(MessageConstant.CANNOT_BE_EMPTY);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
